package common

import (
	"fmt"
	"log"
	"strconv"
	"strings"
)

// ID is ipv4's IP
type ID [4]byte

func ParseIP(s string) ID {
	if s == "<nil>" {
		return ID{0, 0, 0, 0}
	}
	ss := strings.Split(s, ".")
	id := ID{0, 0, 0, 0}
	for i := 0; i < 4; i++ {
		t, err := strconv.ParseUint(ss[i], 10, 8)
		id[i] = uint8(t)
		if err != nil {
			log.Println("can not parse ip: invalid ip address.")
		}
	}
	return id
}

func ParseCIDR(s string) ID {
	if s == "<nil>" {
		return ID{0, 0, 0, 0}
	}
	return ParseIP(s[:len(s)-3])
}

func CIDR(id ID) ID {
	id[3] = 0
	return id
}

func (id ID) String() string {
	return fmt.Sprintf("%v.%v.%v.%v", id[0], id[1], id[2], id[3])
}

func (id ID) StringCIDR() string {
	return fmt.Sprintf("%v.%v.%v.0/24", id[0], id[1], id[2])
}

func (id ID) IsEqual(other ID) bool {
	for i := 0; i < 4; i++ {
		if id[i] != other[i] {
			return false
		}
	}
	return true
}
